<template>
  <div class="vocabulary-search">
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>词汇查询</span>
          <el-button-group>
            <el-button type="primary" @click="loadQueryHistory">
              <el-icon><refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="danger" @click="clearQueryHistory" :disabled="!queryHistory || queryHistory.length === 0">
              <el-icon><delete /></el-icon>
              清空历史
            </el-button>
          </el-button-group>
        </div>
      </template>

      <statistics-display :loading="loading" :error="error">
        <div class="search-section">
          <el-input
            v-model="searchTerm"
            placeholder="请输入要查询的单词"
            @keyup.enter="searchWord"
            clearable
            size="large"
          >
            <template #append>
              <el-button @click="searchWord" :loading="loading">
                <el-icon><search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>

        <el-card v-if="wordDetails" class="word-result-card">
          <template #header>
            <word-display 
              :word="wordDetails" 
              :active-collapse="activeCollapse"
              @update:active-collapse="val => activeCollapse = val"
            />
          </template>
          
          <word-details :word="wordDetails" />
          
          <div class="word-actions-section">
            <word-actions 
              :word="wordDetails" 
              @pronunciation-play="handlePronunciationPlay"
              @status-updated="handleStatusUpdated"
            />
          </div>
        </el-card>

        <div v-if="queryHistory && queryHistory.length > 0" class="query-history">
          <h3>查询历史</h3>
          <div class="history-items">
            <el-tag
              v-for="item in queryHistory"
              :key="item.id"
              @click="searchFromHistory(item.word)"
              closable
              @close="removeFromHistory(item.word)"
              class="history-tag"
            >
              {{ item.word }}
            </el-tag>
          </div>
        </div>
      </statistics-display>
    </el-card>
  </div>
</template>

<script>
import WordDetails from './WordDetails.vue';
import WordActions from './WordActions.vue';
import StatisticsDisplay from './StatisticsDisplay.vue';
import WordDisplay from './WordDisplay.vue';
import { ElInput, ElButton, ElCard, ElTag, ElMessage, ElIcon } from 'element-plus';
import { Search, Refresh, Delete } from '@element-plus/icons-vue';
import pronunciationUtils from '../utils/pronunciationUtils';

export default {
  name: 'VocabularySearch',
  components: {
    ElInput,
    ElButton,
    ElCard,
    ElTag,
    ElMessage,
    ElIcon,
    Search,
    Refresh,
    Delete,
    WordDetails,
    WordActions,
    StatisticsDisplay,
    WordDisplay
  },
  data() {
    return {
      searchTerm: '',
      searchType: 'exact', // exact, prefix, suffix, similar
      wordDetails: null,
      searchResults: [],
      loading: false,
      error: null,
      queryHistory: [], // 添加查询历史记录
      isPlaying: false,
      pronunciationType: null,
      activeCollapse: 'basic'
    };
  },
  async mounted() {
    // 组件挂载时加载查询历史
    await this.loadQueryHistory();
  },
  methods: {
    handlePronunciationPlay(data) {
      console.log('Playing pronunciation:', data);
    },

    handleStatusUpdated(data) {
      console.log('Word status updated:', data);
      // Could trigger a refresh or other actions if needed
    },

    async loadQueryHistory() {
      try {
        const response = await window.electronAPI.getQueryHistory();
        if (response.success) {
          this.queryHistory = response.data;
        } else {
          console.error('Failed to load query history:', response.error);
        }
      } catch (err) {
        console.error('Error loading query history:', err);
      }
    },

    async clearQueryHistory() {
      try {
        const response = await window.electronAPI.clearQueryHistory();
        if (response.success) {
          this.queryHistory = [];
          ElMessage.success('查询历史已清空');
        } else {
          ElMessage.error('清空查询历史失败: ' + response.error);
        }
      } catch (err) {
        ElMessage.error('清空查询历史时发生错误');
        console.error('Error clearing query history:', err);
      }
    },

    async searchFromHistory(term) {
      this.searchTerm = term;
      await this.searchWord();
    },

    async removeFromHistory(term) {
      try {
        const response = await window.electronAPI.removeQueryHistoryItem(term);
        if (response.success) {
          // 从本地数组中移除
          this.queryHistory = this.queryHistory.filter(item => item.word !== term);
          ElMessage.success('已从历史记录中移除');
        } else {
          ElMessage.error('移除历史记录失败: ' + response.error);
        }
      } catch (err) {
        ElMessage.error('移除历史记录时发生错误');
        console.error('Error removing from history:', err);
      }
    },

    async searchWord() {
      if (!this.searchTerm.trim()) return;

      this.loading = true;
      this.error = null;
      this.wordDetails = null;
      this.searchResults = [];

      try {
        console.log('Starting search for term:', this.searchTerm.trim());
        // First try to get exact word match
        if (this.searchType === 'exact') {
          const response = await window.electronAPI.getWord(this.searchTerm.trim());

          console.log('Exact word search response:', response);

          if (response.success && response.data) {
            console.log('Found exact word match');
            this.wordDetails = response.data;
            // Add to query history
            await window.electronAPI.addQueryHistory(this.searchTerm.trim());
            // 重新加载查询历史
            await this.loadQueryHistory();
          } else {
            console.log('No exact match found, trying fuzzy search');
            // If no exact match, try fuzzy search
            const fuzzyResponse = await window.electronAPI.searchWords(this.searchTerm.trim(), 'similar');
            
            console.log('Fuzzy search response:', fuzzyResponse);
            
            if (fuzzyResponse.success && fuzzyResponse.data && fuzzyResponse.data.length > 0) {
              console.log('Found fuzzy matches');
              this.searchResults = fuzzyResponse.data;
            } else {
              console.log('No matches found at all');
              this.error = '未找到匹配的单词';
            }
          }
        } else {
          // For other search types, use searchWords API
          const response = await window.electronAPI.searchWords(this.searchTerm.trim(), this.searchType);
          
          console.log('Search response for type', this.searchType, ':', response);
          
          if (response.success) {
            if (response.data && response.data.length > 0) {
              if (this.searchType === 'exact' && response.data.length === 1) {
                // If exact search with one result, show details
                this.wordDetails = response.data[0];
              } else {
                // Otherwise show list of results
                this.searchResults = response.data;
              }
            } else {
              this.error = '未找到匹配的单词';
            }
          } else {
            this.error = response.error || '查询失败';
          }
        }
      } catch (err) {
        console.error('Search error:', err);
        this.error = err.message || '查询过程中发生错误';
      } finally {
        this.loading = false;
      }
    },

    async playPronunciation(word, type = 'uk') {
      try {
        this.isPlaying = true;
        this.pronunciationType = type;
        await pronunciationUtils.playPronunciation(word, type);
      } catch (err) {
        console.error('Pronunciation error:', err);
        ElMessage.error('发音播放失败: ' + (err.message || '未知错误'));
      } finally {
        this.isPlaying = false;
        this.pronunciationType = null;
      }
    }
  }
};
</script>

<style scoped>
.vocabulary-search {
  max-width: 800px;
  margin: 0 auto;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  font-size: 18px;
  color: #333;
}

.search-box {
  margin-bottom: 20px;
}

.search-options {
  margin-bottom: 20px;
}

.query-history {
  margin-bottom: 20px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.history-header h4 {
  margin: 0;
  color: #555;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.history-tag {
  cursor: pointer;
}

.search-input {
  width: 100%;
}


.error-alert {
  margin-bottom: 20px;
}

.search-results {
  margin-top: 20px;
}

.search-results h3 {
  margin-top: 0;
  color: #333;
}
</style>
